﻿using MyoSharp.Communication;
using MyoSharp.Device;
using MyoSharp.Exceptions;
using MyoSharp.Poses;
using System;
using System.Windows;

namespace MyoSharp.HackNighter
{
    /// <summary>
    /// Interaction logic for MyoMap.xaml
    /// </summary>
    public partial class MyoMap : Window
    {
        public MyoMap()
        {
            InitializeComponent();
            Loaded += MyoMap_Loaded;
        }

        private void MyoMap_Loaded(object sender, RoutedEventArgs e)
        {
            InitializeMyo();
        }

        private void InitializeMyo()
        {
            var channel = Channel.Create(ChannelDriver.Create(ChannelBridge.Create(), MyoErrorHandlerDriver.Create(MyoErrorHandlerBridge.Create())));

            var hub = Hub.Create(channel);
            hub.MyoConnected += (sender, e) =>
            {
                e.Myo.Vibrate(VibrationType.Short);
                e.Myo.Unlock(UnlockType.Hold);

                var heldPose = HeldPose.Create(e.Myo, Pose.WaveIn, Pose.WaveOut, Pose.FingersSpread, Pose.Fist);
                heldPose.Interval = TimeSpan.FromSeconds(0.5);
                heldPose.Start();
                heldPose.Triggered += Pose_Triggered;

                e.Myo.PoseChanged += Myo_PoseChanged;
            };

            hub.MyoDisconnected += (sender, e) =>
            {
                e.Myo.PoseChanged -= Myo_PoseChanged;
            };

            channel.StartListening();
        }

        private void Myo_PoseChanged(object sender, PoseEventArgs e)
        {

        }

        private void Pose_Triggered(object sender, PoseEventArgs e)
        {
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                switch (e.Myo.Pose)
                {
                    case Pose.WaveIn:
                        var latitud1 = this.Map.Center.Latitude;
                        var longitude1 = this.Map.Center.Longitude -= 5;
                        this.Map.Center = new Microsoft.Maps.MapControl.WPF.Location(latitud1, longitude1);
                        break;
                    case Pose.WaveOut:
                        var latitud2 = this.Map.Center.Latitude;
                        var longitude2 = this.Map.Center.Longitude += 5;
                        this.Map.Center = new Microsoft.Maps.MapControl.WPF.Location(latitud2, longitude2);
                        break;
                    case Pose.FingersSpread:
                        this.Map.ZoomLevel++;
                        break;
                    case Pose.Fist:
                        this.Map.ZoomLevel--;
                        break;
                }
            }));
        }
    }
}